package org.dromara.controller;

import lombok.extern.slf4j.Slf4j;
import org.dromara.dto.DataInsertRequest;
import org.dromara.dto.DataInsertResponse;
import org.dromara.entity.Result;
import org.dromara.service.QuestDbService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * REST控制器，处理与QuestDB数据插入相关的API请求
 */
@Slf4j
@RestController
@RequestMapping("/api/questdb")
public class QuestDbController {

    private final QuestDbService questDbService;

    public QuestDbController(QuestDbService questDbService) {
        this.questDbService = questDbService;
    }

    /**
     * 处理数据插入请求的API接口
     *
     * @param request 包含日期文件夹、开始时间、结束时间等参数的请求对象
     * @return 包含操作结果的响应对象
     */
    @CrossOrigin
    @PostMapping("/insert")
    public Result insertData(@RequestBody @Validated DataInsertRequest request) {
        try {
            // 解析日期时间参数
            LocalDateTime startTime = request.getStartTime();
            LocalDateTime endTime = request.getEndTime();
            String ipAddress = request.getQuestdbUrl();

            // 获取并转换questdbUrl
            String questdbUrl = request.getQuestdbUrl();
            if (!questdbUrl.startsWith("jdbc:postgresql://")) {
                questdbUrl = "jdbc:postgresql://" + questdbUrl + ":8812/qdb";
            }
            log.info("当前连接的questdbUrl: {}", questdbUrl);

            // 调用服务层执行数据插入
            DataInsertResponse response = questDbService.insertData(
                    request.getBasePath(),
                    request.getDateFolder(),
                    startTime,
                    endTime,
                    request.getProjectId(),
                    request.getDevId(),
                    request.getTaskId(),
                    questdbUrl,
                    request.getTargetFolder(),
                    ipAddress
            );

            return Result.ok(response);
        } catch (Exception e) {
            log.error("数据插入异常: {}", e.getMessage());
            return Result.fail(e.getMessage());
        }
    }
}
